<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StaffService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $surname = isset($data['surname']) ? $data['surname'] : '';
        $given_name = isset($data['given_name']) ? $data['given_name'] : '';
        $email = isset($data['email']) ? $data['email'] : '';
        $role = isset($data['role']) ? $data['role'] : '';
        $where = ['group_id'=>['<',10000],'u.id'=>['>',1]];
        if($surname)$where['surname'] = ['like', '%'.$surname.'%'];
        if($given_name)$where['given_name'] = ['like', '%'.$given_name.'%'];
        if($email)$where['email'] = ['like', '%'.$email.'%'];
        if($role)$where['group_id'] = $role;

        // return $where;
        //分页查询
        $studio = \app\admin\model\User::alias('u')->join('__USER_GROUP__ ug','u.group_id= ug.id')
            ->where($where)->field('u.*,ug.name,u.staff_status as status')->order('u.id', 'desc')
            ->paginate($limit);
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 添加
    public static function add($data)
    {
        $data['mobile'] = $data['phone'];
        unset($data['phone']);
        $auth = Auth::instance();
        // 验证规则
        $validate = new Validate([
//            'staff_id' => 'require',
            'studio_id' => 'require',
            'group_id' => 'require',
            'surname' => 'require',
            'given_name' => 'require',
//            'english_name' => 'require',
            'gender' => 'require',
            'birthday' => 'require',
            'nationality' => 'require',
            'duty' => 'require',
            'category_focus' => 'require',
            'status' => 'require',
            'highest_education_level' => 'require',
            'education_major' => 'require',
            'email' => 'require|unique:user,email',
            'mobile' => 'require|unique:user,mobile',
            'password' => 'require',
//            'rules' => 'require',
        ], [
//            'staff_id.require' => 'StaffId is not empty',
            'studio_id.require' => 'StudioIdD is not empty',
            'group_id.require' => 'Role is not empty',
            'surname.require' => 'Surname is not empty',
            'given_name.require' => 'Given name is not empty',
//            'english_name.require' => 'English name is not empty',
            'gender.require' => 'Gender is not empty',
            'birthday.require' => 'Birthday is not empty',
            'nationality.require' => 'Nationality is not empty',
            'duty.require' => 'Duty is not empty',
            'category_focus.require' => 'Category Focuse is not empty',
            'status.require' => 'Status is not empty',
            'highest_education_level.require' => 'Fighest Education Level is not empty',
            'education_major.require' => 'Education Major is not empty',
            'email.require' => 'Email is not empty',
            'email.require' => 'Email is already exists',
            'mobile.require' => 'Mobile is not empty',
            'mobile.require' => 'Mobile is already exists',
            'password.require' => 'Password is not empty',

        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 检测用户名、昵称、邮箱、手机号是否存在
        if (User::getByUsername($data['email'])) {
            return ['code'=>400, 'msg'=>'Email already exist', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        if (User::getByNickname($data['email'])) {
            return ['code'=>400, 'msg'=>'Nickname already exist', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        if ($data['email'] && User::getByEmail($data['email'])) {
            return ['code'=>400, 'msg'=>'Email already exist', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        if ($data['mobile'] && User::getByMobile($data['mobile'])) {
            return ['code'=>400, 'msg'=>'Mobile already exist', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            $count = \app\admin\model\User::count();
            $result = $auth->register($data['email'], $data['password'], $data['email'], $data['mobile'],
                [
                    'staff_id'=>$data['studio_id'] . '-S' . ($count+1),
                    'group_id'=>$data['group_id'],
                    'studio_id'=>$data['studio_id'],
                    'surname'=>$data['surname'],
                    'given_name'=>$data['given_name'],
                    // 'english_name'=>$data['english_name'],
                    'avatar'=>$data['avatar'],
                    'gender'=>$data['gender'],
                    'birthday'=>$data['birthday'],
                    'nationality'=>$data['nationality'],
                    'duty'=>$data['duty'],
                    'category_focus'=>$data['category_focus'],
                    'staff_status'=>$data['status'],
                    'highest_education_level'=>$data['highest_education_level'],
                    'education_major'=>$data['education_major'],
                    'plaintext'=>$data['password'],
                ]
            );
            // 后期补权限问题

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 编辑
    public static function edit($data)
    {
//        return $data;
        $data['mobile'] = $data['phone'];
        $data['avatar'] = $data['avatar'];
        unset($data['phone']);

        $auth = Auth::instance();
        // 验证规则
        $validate = new Validate([
            'studio_id' => 'require',
            'group_id' => 'require',
            'surname' => 'require',
            'given_name' => 'require',
//            'english_name' => 'require',
            'gender' => 'require',
            'birthday' => 'require',
            'nationality' => 'require',
            'duty' => 'require',
            'category_focus' => 'require',
            'status' => 'require',
            'highest_education_level' => 'require',
            'education_major' => 'require',
            'email' => 'unique:user,email',
            'mobile' => 'unique:user,mobile',
            // 'password' => 'require',
//            'rules' => 'require',
        ], [
            'studio_id.require' => 'StudioIdD is not empty',
            'group_id.require' => 'Role is not empty',
            'surname.require' => 'Surname is not empty',
            'given_name.require' => 'Given name is not empty',
//            'english_name.require' => 'English name is not empty',
            'gender.require' => 'Gender is not empty',
            'birthday.require' => 'Birthday is not empty',
            'nationality.require' => 'Nationality is not empty',
            'duty.require' => 'Duty is not empty',
            'category_focus.require' => 'Category Focuse is not empty',
            'status.require' => 'Status is not empty',
            'highest_education_level.require' => 'Fighest Education Level is not empty',
            'education_major.require' => 'Education Major is not empty',
            // 'email.require' => 'Email is not empty',
            'email.unique' => 'Email is already exists',
            // 'mobile.require' => 'Mobile is not empty',
            'mobile.unique' => 'Mobile is already exists',
            // 'password.require' => 'Password is not empty',

        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            if(isset($data['password'])) $data['plaintext'] = $data['password'];

            $data['username'] = $data['email'];
            $result = \app\admin\model\User::update($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字

        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        if($data['id'] == 1) return ['code'=>400, 'msg'=>'Cannot be deleted', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        // 查询学习馆数据
        $role = \app\admin\model\User::find($data['id']);
        if (!$role) {
            return ['code'=>400, 'msg'=>'Staff does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }


        // 启用事务删除数据
        try {
            $result = \app\admin\model\User::destroy($data['id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    public static function select($data)
    {
        // 检查 country_code 是否存在并赋默认值
        $countryCode = isset($data['country_code']) ? $data['country_code'] : '';

        // 安全过滤 country_code（假设是 ISO 国家码，如 CN、US）
        if (!preg_match('/^[A-Z]{0,2}$/i', $countryCode)) {
            return ['code' => 400, 'msg' => 'Invalid country code', 'state' => 'ERROR'];
        }

        // 定义 region_code 常量或直接提取为变量
        $fieldRegionCode = 'region_code';

        // 查询逻辑
        if (empty($countryCode)) {
            $regions = \app\admin\model\Regions::where($fieldRegionCode, 'not like', '%-%')->select();
        } else {
            $regions = \app\admin\model\Regions::where($fieldRegionCode, 'like', "%{$countryCode}-%")->select();
        }

        // 返回结果
        if ($regions) {
            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $regions];
        }

        return ['code' => 204, 'msg' => 'No content', 'state' => 'EMPTY', 'data' => $regions];
    }


}
